#include "camera_proc.h"
#include "esp_err.h"
#include "io_proc.h"
#include "esp_camera.h"
#include "pin_map.h"
#include <esp_log.h>
#include "disp_proc.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#define TAG "camrea"

esp_err_t camera_device_init(void)
{
    dvp_pwdn(0);
    camera_config_t config;

    config.ledc_channel = LEDC_CHANNEL_1;  // LEDC通道选择  用于生成XCLK时钟 但是S3不用
    config.ledc_timer = LEDC_TIMER_1; // LEDC timer选择  用于生成XCLK时钟 但是S3不用
    config.pin_d0 = CAMERA_PIN_D0;
    config.pin_d1 = CAMERA_PIN_D1;
    config.pin_d2 = CAMERA_PIN_D2;
    config.pin_d3 = CAMERA_PIN_D3;
    config.pin_d4 = CAMERA_PIN_D4;
    config.pin_d5 = CAMERA_PIN_D5;
    config.pin_d6 = CAMERA_PIN_D6;
    config.pin_d7 = CAMERA_PIN_D7;
    config.pin_xclk = CAMERA_PIN_XCLK;
    config.pin_pclk = CAMERA_PIN_PCLK;
    config.pin_vsync = CAMERA_PIN_VSYNC;
    config.pin_href = CAMERA_PIN_HREF;
    config.pin_sccb_sda = -1;   // 这里写-1 表示使用已经初始化的I2C接口
    config.pin_sccb_scl = -1;
    config.sccb_i2c_port = 0;
    config.pin_pwdn = CAMERA_PIN_PWDN;
    config.pin_reset = CAMERA_PIN_RESET;
    config.xclk_freq_hz = XCLK_FREQ_HZ;
    config.pixel_format = PIXFORMAT_RGB565;
    config.frame_size = FRAMESIZE_QVGA;
    config.jpeg_quality = 12;
    config.fb_count = 2;
    config.fb_location = CAMERA_FB_IN_PSRAM;
    config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;

    esp_err_t err = esp_camera_init(&config);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "camrea init failed with error 0x%x", err);
        return err;
    }

    sensor_t *s = esp_camera_sensor_get();
    if (s->id.PID == GC0308_PID) {
        s->set_hmirror(s, 1);
    }

    return err;

}

static void camera_process_task(void *argv)
{
    while(1) {
        camera_fb_t *frame = esp_camera_fb_get();
        if (frame) {
            disp_camera_push(&frame);
        }
    }
}

void camera_process_create(void)
{
    xTaskCreatePinnedToCore(camera_process_task, "camera_task", 3 * 1024, NULL, 5, NULL, 1);
}